#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/7/12 14:45
# @File    : canvas_alpha.py
# @Description : -i http://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host pypi.tuna.tsinghua.edu.cn


from tkinter import Tk, Canvas
from PIL import Image, ImageTk


def tk_alpha():

    root = Tk()
    root.geometry("400x400+100+100")  # WIDTHxHEIGHT+X+Y
    canvas = Canvas(root)
    canvas.create_rectangle(20, 50, 200, 300, outline="black",
                           width=2, fill='red')
    canvas.create_rectangle(30, 60, 300, 100, outline="black",
                           width=2, activefill='skyblue',  activestipple="gray50")

    # activefill 选择颜色
    canvas.create_rectangle(50, 120, 150, 50, width=0,  activefill='skyblue',  activestipple="gray50")
    canvas.pack(fill='both', expand=1)

    root.mainloop()

def pil_alpha():


    images = []  # to hold the newly created image


    def create_rectangle(x1, y1, x2, y2, **kwargs):
        if 'alpha' in kwargs:
            alpha = int(kwargs.pop('alpha') * 255)
            fill = kwargs.pop('fill')
            fill = root.winfo_rgb(fill) + (alpha,)
            image = Image.new('RGBA', (x2-x1, y2-y1), fill)
            images.append(ImageTk.PhotoImage(image))
            canvas.create_image(x1, y1, image=images[-1], anchor='nw')
        canvas.create_rectangle(x1, y1, x2, y2, **kwargs)


    root = Tk()
    root.geometry("400x400+100+100")  # WIDTHxHEIGHT+X+Y
    canvas = Canvas(root)

    create_rectangle(10, 10, 200, 100, fill='blue')
    create_rectangle(50, 50, 250, 150, fill='green', alpha=.5)
    create_rectangle(80, 80, 150, 120, fill='skyblue', alpha=.8)
    canvas.pack(fill='both', expand=1)


    root.mainloop()


if __name__ == '__main__':

    tk_alpha()